package cn.felord.security.autoconfigure.context;

import cn.felord.security.autoconfigure.LoginAntPathPatterns;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * @author felord.cn
 * @since 2021/8/6 17:26
 */
public class ClientContextFilter extends OncePerRequestFilter {

    private final RequestMatcher requestMatcher;

    public ClientContextFilter() {
        this(new OrRequestMatcher(Arrays.stream(LoginAntPathPatterns.values())
                .map(loginAntPathPattern -> new AntPathRequestMatcher(loginAntPathPattern.pattern(), "POST"))
                .toArray(AntPathRequestMatcher[]::new)));
    }

    public ClientContextFilter(RequestMatcher requestMatcher) {
        this.requestMatcher = requestMatcher;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (this.requestMatcher.matches(request)) {
            Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, "");
            String clientId = (String) parameters.remove("clientId");
            if (!StringUtils.hasText(clientId)) {
                throw new BadCredentialsException("clientId is required");
            }
            ClientContext clientContext = new ClientContext(clientId);
            clientContext.addAllAttribute(parameters);
            ClientContextHolder.setContext(clientContext);
        }

        try {
            filterChain.doFilter(request, response);
        } finally {
            ClientContextHolder.clearContext();
        }
    }
}
